<template>
  <div class="wrapLimit clx main">
    <div>
      <div class="transportCapacityRecord">
        <!-- isCarrier {{isCarrier}} -->
        <el-form ref="inputModel" :rules="rules" :model="inputModel" class="form-baseinfo">
          <div class="insertInfo">
            <p class="title">下单基本信息</p>
            <div class="info">
              <el-form-item label="下单人姓名" prop="userName">
                <el-input v-model="inputModel.userName" />
              </el-form-item>
              <el-form-item label="联系电话" prop="userMobile">
                <el-input v-model="inputModel.userMobile" />
              </el-form-item>
              <el-form-item label="厂区名称" prop="plantName">
                <el-input v-model="inputModel.plantName" />
              </el-form-item>
              <el-form-item label="所属部门" prop="departmentName">
                <el-input v-model="inputModel.departmentName" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="inputModel.remark" />
              </el-form-item>
              <el-form-item label="可送货时间" prop="deliverTime">
                <el-date-picker
                  v-model="inputModel.deliverTime"
                  style="width: 100%"
                  type="date"
                  placeholder="不填默认：不限制时间"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>

        <el-form
          ref="ordersProducts"
          :rules="rules"
          :inline="true"
          :model="inputModel.ordersProducts"
          label-width="90px"
          class="form-baseinfo"
        >
          <div class="insertInfo">
            <p class="title">产品信息</p>
            <div class="info">
              <!-- <el-form-item label="产品类型" prop="categoryNo">
                        <el-select filterable clearable style="width: 130px;" v-model="inputModel.ordersProducts.categoryNo"
                            @change="centreTypeChange">
                            <el-option v-for="item in centreType" :key="item.id" :value="item.categoryNo"
                                :label="item.cName">
                            </el-option>
                        </el-select>
                    </el-form-item> -->
              <el-form-item label="物料名称" prop="pNo">
                <el-select v-model="inputModel.ordersProducts.pNo" filterable clearable>
                  <el-option
                    v-for="item in smallType"
                    :key="item.id"
                    :value="item.pNo"
                    :label="item.pTitle"
                    :disabled="item.plbQuantity == 0 ? true : false"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="购买数量" prop="pCount" style="margin-left: -10px">
                <el-input v-model="inputModel.ordersProducts.pCount" />
              </el-form-item>
              <el-form-item label="员工工号" prop="userJobNum" style="margin-left: -10px">
                <el-input v-model="inputModel.ordersProducts.userJobNum" />
                <el-button class="addBtn" size="medium" type="text" @click="insertData('ordersProducts')"
                  >+ 添加</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button style="width: 100px" size="medium" type="primary" @click="exportInfoDailog = true"
                  >导入</el-button
                >
              </el-form-item>
            </div>
          </div>
          <LPTablePage
            :show-index="true"
            :show-indexfixed="false"
            index-label="序号"
            :table-data="tableData"
            :table-column="tableColumn"
            :total="total"
            :current-page="currentPage"
            :show-page="false"
            height="500"
            align="center"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          >
            <template slot="couponName" slot-scope="{ row }">
              <div v-for="(item, index) in row.couponName" :key="index">
                <el-link type="primary" @click="goToCouponManage(item.id)">{{ item.couponName }}</el-link>
              </div>
            </template>
            <template slot="couponRecordId" slot-scope="{ row }">
              <div v-for="(item, index) in row.couponRecordId" :key="index">
                <div>{{ item.id }}</div>
              </div>
            </template>
            <template slot="cz" slot-scope="scope">
              <el-button type="text" @click="deleteInfo(scope.$index)">删除</el-button>
            </template>
          </LPTablePage>
          <span class="collect"
            >汇总：一共{{ tableCount }}件商品，总金额{{ Math.round(totalMoney * 100) / 100 }}元</span
          >
          <div class="form-baseinfo">
            <el-button class="button" size="medium" @click="close()">关闭</el-button>
            <el-button class="button" size="medium" type="primary" @click="Save('inputModel')">提交</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <el-dialog
      class=""
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="exportInfoDailog"
      width="520px"
      :before-close="uploadCancel"
    >
      <div v-if="!exportError">
        <div style="display: flex; justify-content: center">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :action="public_config.file_api + `/api/file-management/files/upload`"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :show-file-list="true"
            :headers="headers"
            :limit="1"
            :on-exceed="handleExceed"
            :before-remove="beforeRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :on-error="handleError"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </div>
        <el-button style="margin-left: 60px" type="text" @click="exportInfo">下载导入模板</el-button>
        <div style="color: crimson; font-size: 12px">
          导入要求:
          <div style="margin-top: 8px">1、员工工号：每行只允许填写一个</div>
          <div>2、物料编码：需录入具体物料的编码（不能是物料小/中/大类编码），且只能录入一个</div>
          <div>3、数量：正整数，大于0</div>
        </div>
      </div>
      <div v-else>
        <div v-for="(item, index) in errList" :key="index">
          <div style="color: crimson">{{ index + 1 + '、' + item }}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="uploadCancel">取 消</el-button>
        <el-button v-if="!exportError" type="primary" size="medium" @click="uploadSave">保存</el-button>
        <el-button v-else type="primary" size="medium" @click="uploadAgain">重新导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { download } from '@/utils/lpUtils'
import { getCategoryInfo } from '@/api/LaborProtection/categoryInfo'
import { getProductList } from '@/api/LaborProtection/product'
import {
  insertAndupdateRemoteOrder,
  getEmployee,
  getCouponByUser,
  getUserName,
  exportRemoteOrderDemo,
  importMaterial,
  getBalance
} from '@/api/LaborProtection/order'
import { closeActiveTag, parseTime } from '@/utils/lpUtils.js'
import LPTablePage from '@/components/LPTablePage/index.vue'

export default {
  name: 'RemoteOrderInsertOrder',
  components: { LPTablePage },
  data() {
    return {
      headers: {
        Authorization: 'bearer ' + getToken()
      },
      inputModel: {
        userName: '',
        userJobNum: '',
        userMobile: '',
        plantName: '',
        departmentName: '',
        jobName: '',
        deliverTime: '',
        remark: '',
        ordersProducts: {
          pNo: '',
          categoryNo: '',
          userName: '',
          userJobNum: '',
          pCount: ''
        }
      },
      data: {},
      tableData: [],
      tableColumn: [
        { label: '物料类型', prop: 'cName' },
        { label: '物料编码', prop: 'pNo' },
        { label: '物料名称', prop: 'pTitle' },
        { label: '单位', prop: 'pUnit', width: 60 },
        { label: '数量', prop: 'pCount', width: 60 },
        { label: '物料销售单价', prop: 'pPrice', width: 120 },
        { label: '下单金额', prop: 'pAmount', width: 80 },
        // { label: "优惠券名称", prop: "couponName", width: 140, render: true },
        // { label: "优惠券发放编号", prop: "couponRecordId", width: 140, render: true },
        { label: '员工工号', prop: 'userJobNum', width: 120 },
        { label: '员工卡号', prop: 'userCardNo', width: 120 },
        { label: '员工姓名', prop: 'realName' },
        { label: '操作', prop: 'cz', render: true }
      ],
      title: '导入远程单产品',
      exportError: false,
      errList: [],
      options: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      PID: 0,
      tableCount: 0,
      totalMoney: 0,
      exportInfoDailog: false,
      bigType: [],
      payType: '1',
      fileList: [],
      centreType: [],
      smallType: [],
      orderFlagType: [],
      rules: {
        userName: [{ required: true, message: '请输入下单人姓名', trigger: 'blur' }],
        userMobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        plantName: [{ required: true, message: '请输入厂区名称', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请输入所属部门', trigger: 'blur' }],
        pNo: [{ required: true, message: '请选择物料名称', trigger: 'blur' }],
        userJobNum: [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
        pCount: [{ required: true, message: '请输入购买数量', trigger: 'blur' }],
        categoryNo: [{ required: true, message: '请选择物料类型', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getUserName()
    this.getCategoryInfo(2)
    this.getProductList(1)
    this.getProductList(0)
  },
  methods: {
    getUserName() {
      const param = {
        name: this.$store.getters.name
      }
      getUserName(param).then((res) => {
        this.inputModel.userName = res.realName
        this.inputModel.departmentName = res.departmentName
      })
    },
    /**
     *  1：大类 2：中类 3：小类
     * @param {*} type
     */
    getCategoryInfo(type) {
      const data = {
        CCLass: type,
        SkipCount: 0
      }
      getCategoryInfo(data).then((res) => {
        if (!res.error) {
          this.centreType = res.items
        }
      })
    },
    /**
     * 取下单时物料名称下拉框
     * @param {*} QCategoryNo
     */
    getProductList(type, QCategoryNo) {
      const params = {
        PType: type,
        // QCategoryNo: QCategoryNo,
        SkipCount: 0
      }
      getProductList(params).then((res) => {
        if (type == 1) {
          this.smallType = res.items
        } else if (type == 0) {
          this.orderFlagType = res.items
        }
      })
    },
    centreTypeChange() {
      this.inputModel.ordersProducts.pNo = ''
      if (this.inputModel.ordersProducts.categoryNo == '') {
        this.smallType = []
      } else {
        this.getProductList(this.inputModel.ordersProducts.categoryNo)
      }
    },
    handleSearchSubmit() {
      this.currentPage = 1
    },
    handleSearchReset() {
      this.handleSearchSubmit()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
    },
    handleError(err, file, fileList) {
      return this.$message.error(err)
    },
    exportInfo() {
      const params = {}
      exportRemoteOrderDemo(params).then((res) => {
        download(res, '远程下单产品模板')
        this.$message.success('下载模板成功')
      })
    },
    uploadSave() {
      const data = {
        fileUrl: this.url,
        fileName: this.fileName
      }

      if (this.url == '' || this.fileName == '') {
        return this.$message.error('请上传文件')
      }

      importMaterial(data).then((res) => {
        if (res.errList == null) {
          const dataList = []
          const uniqueData = []
          // 数据去重
          res.orderCouponItemDtos.forEach((item) => {
            const tempData = uniqueData.find(
              (uniqueItem) =>
                uniqueItem.jobNum === item.jobNum &&
                uniqueItem.cardNo === item.cardNo &&
                uniqueItem.realName === item.realName &&
                uniqueItem.materialCode === item.materialCode
            )
            if (!tempData) {
              uniqueData.push(item)
            }
          })
          // 数据去和员工信息绑定
          uniqueData.forEach((item) => {
            res.orderCouponItemDtos.forEach((tempItem) => {
              if (
                item.jobNum == tempItem.jobNum &&
                item.cardNo === tempItem.cardNo &&
                item.realName === tempItem.realName &&
                item.materialCode === tempItem.materialCode
              ) {
                if (this.payType == '0') {
                  if (item.couponName != tempItem.couponName && item.couponRecordId != tempItem.couponRecordId) {
                    item.countOk = item.countOk + tempItem.countOk
                    item.couponRecordId1 = [{ id: tempItem.couponRecordId }]
                    item.couponName1 = [{ couponName: tempItem.couponName, id: tempItem.couponId }]
                  }
                }
              }
            })
          })
          // 数据去和物料信息绑定拿到单位、单价、计算金额
          uniqueData.forEach((item) => {
            this.orderFlagType.forEach((tempItem) => {
              if (tempItem.pNo == item.materialCode) {
                item.pUnit = tempItem.pUnit
                item.pPrice = Math.round(tempItem.pPrice * 100) / 100
                if (this.payType == '0') {
                  item.pAmount = Math.round(tempItem.pPrice * Number(item.countOk) * 100) / 100
                } else {
                  console.log(2, item.count)
                  item.pAmount = Math.round(tempItem.pPrice * Number(item.count) * 100) / 100
                }
              }
            })
            this.totalMoney = this.totalMoney + item.pAmount

            if (this.payType == '0') {
              this.tableCount = this.tableCount + item.countOk
              if (item.couponRecordId1 != undefined) {
                item.couponRecordId1.push({ id: item.couponRecordId })
              } else {
                item.couponRecordId1 = [{ id: item.couponRecordId }]
              }

              if (item.couponName1 != undefined) {
                item.couponName1.push({ couponName: item.couponName, id: item.couponId })
              } else {
                item.couponName1 = [{ couponName: item.couponName, id: item.couponId }]
              }
            } else {
              console.log(3, item.count)
              this.tableCount = this.tableCount + item.count
            }

            if (this.payType == '0') {
              dataList.push({
                realName: item.realName,
                userCardNo: item.cardNo,
                userJobNum: item.jobNum,
                couponRecordId: item.couponRecordId1,
                couponName: item.couponName1,
                pAmount: item.pAmount,
                pPrice: item.pPrice,
                pCount: item.countOk,
                pUnit: item.pUnit,
                pTitle: item.materialName,
                pNo: item.materialCode,
                cName: item.middleCName
              })
            } else {
              dataList.push({
                realName: item.realName,
                userCardNo: item.cardNo,
                userJobNum: item.jobNum,
                pAmount: item.pAmount,
                pPrice: item.pPrice,
                pCount: item.count,
                pUnit: item.pUnit,
                pTitle: item.materialName,
                pNo: item.materialCode,
                cName: item.middleCName
              })
            }
          })
          this.tableData = dataList
          this.exportInfoDailog = false
          this.$message.success('导入成功')
        } else {
          this.title = '导入错误'
          this.exportError = true
          this.errList = res.errList
        }
      })
    },
    uploadAgain() {
      this.title = '导入远程单产品'
      this.exportError = false
      this.errList = []
    },
    uploadCancel() {
      this.exportInfoDailog = false
      this.url = ''
      this.fileName = ''
      this.title = '导入远程单产品'
      this.exportError = false
      this.errList = []
      this.fileList = []
    },
    handleRemove(file, fileList) {
      this.fileList = []
      this.fileName = ''
      this.url = ''
    },
    handlePreview(file) {},
    handleExceed() {
      this.$message.warning(`限制选择 1 个文件`)
    },
    beforeRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleSuccess(res, file) {
      this.url = public_config.file_api + '/api/file-management/files/www/' + file.response
      this.fileName = file.name
    },
    handleCurrentChange(v) {
      this.currentPage = v
    },
    initialData() {
      this.inputModel.ordersProducts = {
        pNo: '',
        categoryNo: '',
        userName: '',
        userJobNum: '',
        pCount: ''
      }
    },

    insertData(ordersProducts) {
      this.$refs[ordersProducts].validate((valid) => {
        if (valid) {
          const params = {
            JobNum: this.inputModel.ordersProducts.userJobNum
          }
          getEmployee(params).then((res) => {
            if (res.realName != null && res.realName != '') {
              const data = {}
              const materialList = {}
              // this.centreType.forEach(item => {
              //     if (item.categoryNo == this.inputModel.ordersProducts.categoryNo) {
              //         data.cName = item.cName;
              //     }
              // });
              this.smallType.forEach((item) => {
                if (item.pNo == this.inputModel.ordersProducts.pNo) {
                  data.pNo = item.pNo
                  data.pTitle = item.pTitle
                  data.pUnit = item.pUnit
                  data.pPrice = Math.round(item.pPrice * 100) / 100
                  data.pAmount = Math.round(item.pPrice * Number(this.inputModel.ordersProducts.pCount) * 100) / 100
                  data.pCount = Number(this.inputModel.ordersProducts.pCount)
                  data.cName = item.pName
                  materialList.qCategoryNo = item.qCategoryNo
                }
              })
              data.userJobNum = this.inputModel.ordersProducts.userJobNum
              data.userCardNo = res.cardNo
              data.realName = res.realName
              materialList.materialName = data.pTitle
              materialList.materialCode = data.pNo
              materialList.materialCodeNumber = data.pCount
              data.couponName = []
              data.couponRecordId = []

              if (this.payType == '0') {
                const data1 = {
                  userNo: this.inputModel.ordersProducts.userJobNum,
                  material: [{ ...materialList }]
                }
                getCouponByUser(data1).then((res1) => {
                  if (res1.mark) {
                    if (res1.orderCouponItemDtos.length > 0) {
                      res1.orderCouponItemDtos.forEach((item) => {
                        data.cName = item.middleCName
                        data.couponName.push({
                          couponName: item.couponName,
                          id: item.couponId
                        })
                        data.couponRecordId.push({
                          id: item.couponRecordId
                        })
                      })
                      const pushFlag = this.tableData.some(
                        (item) =>
                          item.pTitle == data.pTitle &&
                          item.pNo == data.pNo &&
                          item.cName == data.cName &&
                          item.userJobNum == data.userJobNum
                      )
                      if (pushFlag) {
                        return this.$message.error('相同工号下不可购买相同产品')
                      } else {
                        this.totalMoney = this.totalMoney + data.pAmount
                        this.tableCount = this.tableCount + data.pCount
                        this.tableData.push(data)
                        this.initialData()
                      }
                    }
                  } else {
                    return this.$message.error(res1.topic)
                  }
                })
              } else {
                const data1 = {
                  custId: res.custId,
                  custThirdId: ''
                }
                getBalance(data1).then((res1) => {
                  const tempCardMoney = Math.round(res1.accBal) / 100
                  const pushFlag = this.tableData.some(
                    (item) =>
                      item.pTitle == data.pTitle &&
                      item.pNo == data.pNo &&
                      item.cName == data.cName &&
                      item.userJobNum == data.userJobNum
                  )
                  if (pushFlag) {
                    return this.$message.error('相同工号下不可购买相同产品')
                  } else {
                    // 临时的table 用来判断表内 相同工号下所用的金额 与 卡内余额作比较
                    const tempData = JSON.parse(JSON.stringify(this.tableData))
                    tempData.push(data)
                    let tempMoney = 0
                    tempData.forEach((item) => {
                      if (item.userJobNum == data.userJobNum) {
                        tempMoney = tempMoney + item.pAmount
                      }
                    })
                    if (tempMoney > tempCardMoney) {
                      return this.$message.error(`工号：${data.userJobNum},卡内余额不足`)
                    }

                    this.totalMoney = this.totalMoney + data.pAmount
                    this.tableCount = this.tableCount + data.pCount
                    this.tableData.push(data)
                    this.initialData()
                  }
                })
              }
            } else {
              return this.$message.error('员工工号所属无具体人员，请重新输入')
            }
          })
        } else {
          return false
        }
      })
    },
    goToCouponManage(id) {
      this.$router.push({
        path: '/laborProtection/couponManage',
        query: {
          data: JSON.stringify({
            id: id,
            back: '/remoteOrder/components/insertOrder'
          })
        }
      })
    },
    deleteInfo(index) {
      this.$confirm('是否删除该条产品信息', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      })
        .then(({ value }) => {
          this.$message.success('删除成功')
          this.tableData.splice(index, 1)
          this.tableCount = 0
          this.totalMoney = 0
          this.tableData.forEach((item) => {
            this.tableCount = this.tableCount + item.pCount
            this.totalMoney = this.totalMoney + item.pAmount
          })
        })
        .catch(() => {})
    },
    saveFlag() {
      const result = []
      const uniqueData = []
      this.tableData.forEach((item) => {
        if (item.pPrice == undefined) {
          result.push(item)
        }
      })
      result.forEach((item) => {
        const tempData = uniqueData.find((uniqueItem) => uniqueItem.pNo === item.pNo)
        if (!tempData) {
          uniqueData.push(item)
        }
      })
      return uniqueData
    },

    Save(inputModel) {
      const saveFlagResult = this.saveFlag()
      if (saveFlagResult.length > 0) {
        let json = ``
        saveFlagResult.forEach((item) => {
          json += `<div>${item.pTitle} : 库存不足<div>`
        })
        return this.$message.warning({
          dangerouslyUseHTMLString: true,
          message: `${json}`
        })
      }
      this.$refs[inputModel].validate((valid) => {
        if (valid) {
          if (this.tableData.length == 0) {
            return this.$message.error('产品信息至少为一条')
          }
          const ordersProducts = []
          let soMoney = 0
          this.tableData.forEach((item) => {
            soMoney = soMoney + item.pAmount
            ordersProducts.push({
              pNo: item.pNo,
              pCount: item.pCount,
              userJobNum: item.userJobNum
            })
          })
          const data = {
            SOType: 2, // 1 收银台下单 2 远程下单
            userName: this.inputModel.userName,
            userMobile: this.inputModel.userMobile,
            plantName: this.inputModel.plantName,
            departmentName: this.inputModel.departmentName,
            deliverTime: parseTime(this.inputModel.deliverTime),
            soMoney: soMoney,
            remark: this.inputModel.remark,
            ordersProducts: ordersProducts
          }
          if (localStorage.getItem('warehouseType') == null) {
            data.inventoryType = 0
          } else {
            data.inventoryType = 1
          }
          insertAndupdateRemoteOrder(data).then((res) => {
            if (!res.error) {
              this.$message.success('已提交审核')
              this.close()
            }
          })
        } else {
          return false
        }
      })
    },
    close() {
      closeActiveTag(this, '/laborProtection/order/remoteOrder')
    }
  }
}
</script>

<style lang="scss" scoped>
.transportCapacityRecord {
  height: 1400px;
  margin: 0 45px;

  .form-baseinfo {
    ::v-deep .search-bar input.el-input__inner {
      width: 2rem;
    }
    .title {
      font-size: 16px;
      font-weight: 600;
    }
  }
}

::v-deep .el-form-item__label {
  text-align: left;
  font-weight: normal;
  color: #333333;
  line-height: 30px;
}
.insertInfo {
  .info {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: end;
    // margin: 0 45px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ededed;

    .el-form-item {
      display: flex;
      flex-direction: column;
      width: calc(32%);
      height: auto;
      // margin-bottom: 80px;
      &:nth-child(3) {
        position: relative;
      }
    }
    ::v-deep .el-input__inner {
      width: 400px;
      height: 36px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid #d8d8d8;
    }
    .addBtn {
      position: absolute;
      right: 27%;
    }
  }
}
.collect {
  display: block;
  padding-left: 20px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: #f2f3f5;
}
.title {
  margin-left: 10px;
  padding: 20px 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    position: absolute;
    left: 45px;
    background: #0076ff;
  }
}

.button {
  width: 100px;
  position: relative;
  left: 45%;
  top: 30px;
  margin: 0 40px;
  transform: translate(-50%);

  &:nth-of-type(1) {
    color: #333333;
    background-color: #fff;
  }
}
</style>
